#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include "../include/common.h"
#include "../include/platform.h"

#define THREADS 20
#define OPS_PER_THREAD 200

static const char *names[] = {"Alice","Bob","Carol","Dave","Eve","Frank","Grace","Heidi","Ivan","Judy"};

void *worker(void *arg) {
    int tid = (int)(long)arg;
    for (int i = 0; i < OPS_PER_THREAD; ++i) {
        int op = rand() % 3; // 0=login,1=sell,2=buy
        if (op == 0) {
            Command c;
            memset(&c,0,sizeof(c));
            c.type = LOGIN;
            const char *n = names[rand() % (sizeof(names)/sizeof(names[0]))];
            strncpy(c.name, n, NAME_SIZE-1);
            Reply r = execute_cmd(&c);
            if (r.err != SUCCESS) {
                printf("[T%d] LOGIN %s -> err=%d\n", tid, n, r.err);
            }
        } else if (op == 1) {
            // SELL a random good
            Command c;
            memset(&c,0,sizeof(c));
            c.type = SELL;
            const char *n = names[rand() % (sizeof(names)/sizeof(names[0]))];
            strncpy(c.name, n, NAME_SIZE-1);
            c.number = rand() % 100; // price
            c.user_id = platform_add_user(n); // ensure user exists
            snprintf(c.description, DESCRIPTION_SIZE, "Test item from %s tid=%d", n, tid);
            Reply r = execute_cmd(&c);
            if (r.err != SUCCESS) {
                printf("[T%d] SELL -> err=%d\n", tid, r.err);
            }
        } else {
            // BUY random id (1..current goods id + some)
            Command c;
            memset(&c,0,sizeof(c));
            c.type = BUY;
            int tryid = (rand() % 50) + 1; // try ids in [1,50]
            c.id = tryid;
            c.number = 1;
            c.user_id = platform_add_user(names[rand() % (sizeof(names)/sizeof(names[0]))]);
            Reply r = execute_cmd(&c);
            // ignore errors; just print some
            if (r.err == SUCCESS) {
                // occasionally print
                if (rand() % 100 == 0) printf("[T%d] BUY id=%d OK total=%d\n", tid, tryid, r.total_price);
            }
        }
        // small pause
        if ((i & 7) == 0) usleep(1000);
    }
    return NULL;
}

int main(void) {
    srand((unsigned)time(NULL));
    platform_init();

    pthread_t th[THREADS];
    for (long i = 0; i < THREADS; ++i) {
        if (pthread_create(&th[i], NULL, worker, (void *)i) != 0) {
            perror("pthread_create");
            return 1;
        }
    }
    for (int i = 0; i < THREADS; ++i) pthread_join(th[i], NULL);

    platform_close();
    printf("Concurrency test finished\n");
    return 0;
}
